// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Layout from '@/components/Layout.vue';
import Login from '@/views/login/Login.vue';
import Register from '@/views/login/Register.vue';
import Dashboard from '@/views/Dashboard.vue';
import UserList from '@/views/manage/user/UserList.vue';
import AddUser from '@/views/manage/user/AddUser.vue';
import RealTimeControl from '@/views/control/RealTimeControl.vue';
import AutoInspection from '@/views/control/AutoInspection.vue';

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard,
        meta: { requiresAuth: true },
      },
      {
        path: '/userList',
        name: 'UserManagement',
        component: UserList,
        meta: { requiresAuth: true },
      },
      {
        path: '/addUser',
        name: 'AddUser',
        component: AddUser,
        meta: { requiresAuth: true },
      },
      {
        path: '/realTimeControl',
        name: 'RealTimeControl',
        component: RealTimeControl,
        meta: { requiresAuth: true },
      },
      {
        path: '/autoInspection',
        name: 'AutoInspection',
        component: AutoInspection,
        meta: { requiresAuth: true },
      },
      // 其他受保护的路由可以在这里添加
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
  },
  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login',
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('authToken');
  if (to.meta.requiresAuth && !token) {
    next({ name: 'Login' });
  } else if ((to.name === 'Login' || to.name === 'Register') && token) {
    next({ name: 'Dashboard' });
  } else {
    next();
  }
});

export default router;
